package com.gviiii.baiduai.auth;

import cn.hutool.json.JSONUtil;
import com.baidu.aip.face.AipFace;
import com.gviiii.baiduai.config.ConfigRegistry;
import com.gviiii.baiduai.util.HttpClientUtil;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class AuthClient {

    private static volatile AuthClient authClient=null;

    private static Object lock=new Object();


    private AuthClient() {

    }

    public static AuthClient getAuthClient(){
        if (authClient==null){
            synchronized (lock){
                if (authClient==null){
                    return authClient=new AuthClient();
                }
            }
        }
        return authClient;
    }
    /**
     * 获取token，读取配置文件保存配置
     */
    @SuppressWarnings("unchecked")
    public static Map aipEasydlClient(ConfigRegistry configRegistry) {
        Map paraMap = new HashMap();
        paraMap.put("grant_type", "client_credentials");
        paraMap.put("client_id", configRegistry.getConfig("ak"));
        paraMap.put("client_secret", configRegistry.getConfig("sk"));
        String result = HttpClientUtil.httpGetRequest(String.valueOf(configRegistry.getConfig("api")), paraMap);
        if (JSONUtil.isJson(result)) {
            JSONObject jsonObject = new JSONObject(result);
            paraMap.put("accesstoken", jsonObject.getString("access_token"));
            paraMap.put("expiresin", String.valueOf(jsonObject.getLong("expires_in")));
        }
        return paraMap;
    }

    /**
     * 获取AipFace
     * @return
     */
    public static AipFace aipFaceClient(ConfigRegistry configRegistry){
        AipFace aipFace=new AipFace(String.valueOf(configRegistry.getConfig("appid")),String.valueOf(configRegistry.getConfig("ak")),String.valueOf(configRegistry.getConfig("sk")));
        return aipFace;
    }
}
